{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# See a Summary of All Activities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import display, Markdown\n",
    "import snakemd\n",
    "\n",
    "import fitfile\n",
    "from garmindb import GarminConnectConfigManager\n",
    "from garmindb.garmindb import GarminDb, Attributes, ActivitiesDb, Activities, StepsActivities, ActivityLaps, ActivityRecords\n",
    "from idbutils.list_and_dict import list_not_none\n",
    "\n",
    "from jupyter_funcs import format_number\n",
    "\n",
    "gc_config = GarminConnectConfigManager()\n",
    "db_params_dict = gc_config.get_db_params()\n",
    "\n",
    "\n",
    "garmin_db = GarminDb(db_params_dict)\n",
    "garmin_act_db = ActivitiesDb(db_params_dict)\n",
    "measurement_system = Attributes.measurements_type(garmin_db)\n",
    "unit_strings = fitfile.units.unit_strings[measurement_system]\n",
    "distance_units = unit_strings[fitfile.units.UnitTypes.distance_long]\n",
    "\n",
    "def __report_sport(sport_col, sport):\n",
    "    records = Activities.row_count(garmin_act_db, sport_col, sport)\n",
    "    if records > 0:\n",
    "        sport_title = sport.title().replace('_', ' ')\n",
    "        total_distance = Activities.get_col_sum_for_value(garmin_act_db, Activities.distance, sport_col, sport)\n",
    "        if total_distance is None:\n",
    "            total_distance = 0\n",
    "            average_distance = 0\n",
    "        else:\n",
    "            average_distance = total_distance / records\n",
    "        return [sport_title, records, format_number(total_distance, 1), format_number(average_distance, 1)]\n",
    "\n",
    "doc = snakemd.new_doc()\n",
    "\n",
    "doc.add_heading(\"Activities Report\")\n",
    "doc.add_paragraph(\"Analysis of all activities in the database.\")\n",
    "\n",
    "doc.add_table(\n",
    "    ['Type', 'Count'],\n",
    "    [\n",
    "        [\"Total activities\", Activities.row_count(garmin_act_db)],\n",
    "        [\"Total Lap records\", ActivityLaps.row_count(garmin_act_db)],\n",
    "        [\"Activity records\", ActivityRecords.row_count(garmin_act_db)],\n",
    "        [\"Fitness activities\", Activities.row_count(garmin_act_db, Activities.type, 'fitness')],\n",
    "        [\"Recreation activities\", Activities.row_count(garmin_act_db, Activities.type, 'recreation')]\n",
    "    ])\n",
    "\n",
    "years = Activities.get_years(garmin_act_db)\n",
    "years.sort()\n",
    "doc.add_paragraph(f\"Years with activities: {len(years)}: {years}\")\n",
    "sports = list_not_none(Activities.get_col_distinct(garmin_act_db, Activities.sport))\n",
    "doc.add_paragraph(f\"Sports: {', '.join(sports)}\")\n",
    "sub_sports = list_not_none(Activities.get_col_distinct(garmin_act_db, Activities.sub_sport))\n",
    "doc.add_paragraph(f\"SubSports: {', '.join(sub_sports)}\")\n",
    "\n",
    "sports_stats = []\n",
    "for sport_name in [sport.name for sport in fitfile.Sport]:\n",
    "    sport_stat = __report_sport(Activities.sport, sport_name)\n",
    "    if sport_stat:\n",
    "        sports_stats.append(sport_stat)\n",
    "doc.add_heading(\"Sport Type Statistics\", 3)\n",
    "doc.add_table(['Sport', 'Total Activities', f'Total Distance ({distance_units})', f\"Average Distance ({distance_units})\"], sports_stats)\n",
    "\n",
    "def __format_activity(activity):\n",
    "    if activity:\n",
    "        if activity.is_steps_activity():\n",
    "            steps_activity = StepsActivities.get(garmin_act_db, activity.activity_id)\n",
    "            return [activity.activity_id, activity.name, activity.type, activity.sport, format_number(activity.distance, 1), activity.elapsed_time, format_number(activity.avg_speed, 1),\n",
    "                    steps_activity.avg_pace, format_number(activity.calories), format_number(activity.training_load, 1), activity.self_eval_feel, activity.self_eval_effort]\n",
    "        return [activity.activity_id, activity.name, activity.type, activity.sport, format_number(activity.distance, 1), activity.elapsed_time, format_number(activity.avg_speed, 1), '',\n",
    "                format_number(activity.calories), format_number(activity.training_load, 1), activity.self_eval_feel, activity.self_eval_effort]\n",
    "    return ['', '', '', '', '', '', '', '', '']\n",
    "\n",
    "activities = Activities.get_latest(garmin_act_db, 10)\n",
    "rows = [__format_activity(activity) for activity in activities]\n",
    "doc.add_heading(\"Last Ten Activities\", 3)\n",
    "doc.add_table(['Id', 'Name', 'Type', 'Sport', f'Distance ({distance_units})', 'Elapsed Time', f'Speed ({unit_strings[fitfile.units.UnitTypes.speed]})',\n",
    "               f'Pace ({unit_strings[fitfile.units.UnitTypes.pace]})', 'Calories', 'Training Load', 'Feel', 'Effort'], rows)\n",
    "\n",
    "rows = []\n",
    "for display_activity in gc_config.display_activities():\n",
    "    name = display_activity.activity_name().capitalize()\n",
    "    rows.append([f'Latest {name}'] + __format_activity(Activities.get_latest_by_sport(garmin_act_db, display_activity)))\n",
    "    rows.append([f'Fastest {name}'] + __format_activity(Activities.get_fastest_by_sport(garmin_act_db, display_activity)))\n",
    "    rows.append([f'Slowest {name}'] + __format_activity(Activities.get_slowest_by_sport(garmin_act_db, display_activity)))\n",
    "    rows.append([f'Longest {name}'] + __format_activity(Activities.get_longest_by_sport(garmin_act_db, display_activity)))\n",
    "\n",
    "doc.add_heading(\"Interesting Activities\", 3)\n",
    "doc.add_table(['What', 'Id', 'Name', 'Type', 'Sport', f'Distance ({distance_units})', 'Elapsed Time', f'Speed ({unit_strings[fitfile.units.UnitTypes.speed]})',\n",
    "               f'Pace ({unit_strings[fitfile.units.UnitTypes.pace]})', 'Calories', 'Training Load', 'Feel', 'Effort'], rows)\n",
    "\n",
    "doc.add_heading(\"Courses\", 3)\n",
    "courses = Activities.get_col_distinct(garmin_act_db, Activities.course_id)\n",
    "doc.add_paragraph(str(courses))\n",
    "\n",
    "display(Markdown(str(doc)))"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "d4f50e87ad7f9cd136d9d3dcf547b8236ee2585f92d0ab7c53dfb80e44e3fae9"
  },
  "kernelspec": {
   "display_name": "Python 3.9.5 64-bit ('.venv')",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
